<script setup>
import { ref } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { uniFetch } from '../../api/uni-fetch';
import { useUserStore } from "/store/user.js"


const store = useUserStore()

const keyword = ref('')
const total = ref(0)
onLoad(options => {
  if (options.type == '1') {
    handleSearch('【畅销】')
    keyword.value = '【畅销】'
  } else if (options.type == '2') {
    handleSearch('【推荐】')
    keyword.value = '【推荐】'
  } else {
    keyword.value = options.search
    handleSearch(options.search)
  }
})

// 已售随机数     已售假数据
function getOrCreateSoldCount(item) {
  // 从缓存获取
  const cachedCount = uni.getStorageSync(`sold_${item.id}`)
  if (cachedCount) {
		// 首页不增加操作
		item.soldCount = cachedCount
  } else {
    // 首次生成96-400之间的随机数
    item.soldCount = Math.floor(Math.random() * (400 - 96 + 1)) + 96
		// 更新缓存
		uni.setStorageSync(`sold_${item.id}`, item.soldCount)
  }
}

async function handleSearch(search) {
  const { data } = await uniFetch.post('/product/list', {
    app_id: uni.appId,
    page: page.value,
    pageSize: 10,
    search
  })
  // 已售假数据
  if (data?.list && data.list.length > 0) {
		data.list.forEach(item => {
			getOrCreateSoldCount(item)
		})
	}
  data.list.forEach(item => {
    item.id = item.id + '_' + resetKey.value
  })
  items.value.push(...data.list)
  total.value = data.total * resetKey.value
}

const items = ref([])
const page = ref(1)

const resetKey = ref(1)
onReachBottom(() => {
  console.log('触底', total.value > items.value.length)
  if (total.value > items.value.length) {
    page.value++
    handleSearch(keyword.value)
  } else {
    // resetKey.value++ 
    // page.value = 1
    // handleSearch(keyword.value)
    // 当没有更多数据时，只显示提示而不重置page和重新加载
    uni.showToast({
      title: '没有更多商品了',
      icon: 'none'
    })
  }
})

function subSearch(){
  page.value = 1
  items.value = []
  handleSearch(keyword.value)
}

async function addTocart(item) {
  try {
    uni.showLoading({ title: '正在加入购物车...' })
    // 从修改后的id中提取原始id
    const originalProductId = item.id.split('_')[0];
    console.log('原始商品ID:', originalProductId);
    
    const res = await uniFetch.post('/shop-cart/add', {
      product_id: originalProductId,
      count: 1, // 默认数量为1，可根据需要修改
      app_id: uni.appId
    })
    uni.hideLoading()
    
    if (res.code === 10000) {
      uni.showToast({ 
        title: '已加入购物车',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: res.message || '加入购物车失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
    console.error('加入购物车失败:', error)
  }
}

// 跳转详情
function goodsDetail(id) {
	console.log(id);
	uni.navigateTo({
		url: '/pages/ProductDetails/ProductDetails?goodsId=' + id
	});
}

</script>

<template>
  <view class="goods-page">
    <view class="search-bar">
      <input type="text" v-model="keyword" placeholder="请输入搜索关键字" @confirm="subSearch" />
      <button @click="subSearch">搜索</button>
    </view>
    <view class="cate-two-box">
      <view class="goods-card-box" v-for="item in items" :key="item.id" @click="goodsDetail(item.id)">
        <view class="goods-item-img">
          <image :src="item.banner_image" mode="aspectFit"></image>
        </view>
        <view class="goods-item-title">
          {{ item.title }}
        </view>
        <view class="goods-item-buy">
          <view class="goods-item-price" v-if="store.memberInfo.is_member">
            ￥ {{ item.member_price }}
          </view>
          <view class="goods-item-price" v-else>
            ￥ {{ item.price }}
          </view>
          <view class="goods-item-price-old">
            <text class="price">
              ￥{{ item.old_price }}
            </text> <text class="sold">
              <!-- 已售 {{ item.buyer }} -->
              已售 {{ item.soldCount }}
            </text>
          </view>

          <!-- 购物车 -->
          <view class="add-to-cart" @click.stop="addTocart(item)">
            <view class="icon">
              <uni-icons custom-prefix="iconfont" type="icon-gouwuche" color="#fefefe" size="16"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>


<style lang="scss" >
@import '/static/iconfont/iconfont.css';

.goods-page {
  background-color: #f3f3f3;
  width: 100%;

  .search-bar {
    display: flex;
    align-items: center;
    padding: 20rpx;
    // background-color: pink; 

    input {
      flex: 1;
      padding: 0 10rpx;
      height: 65rpx;
      border: 1px solid #ccc;
      border-radius: 4rpx;
      margin-right: 10rpx;
    }

    button {
      height: 65rpx;
      background-color: #333;
      color: #fff;
      border-radius: 4rpx;
      line-height: 65rpx;
      text-align: center;
    }
  }



  .cate-two-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    width: 95%;
    padding: 0 0 25rpx 0;
    margin: 0 auto;

    .goods-card-box {
      margin-top: 15rpx;
      margin-bottom: 15rpx;
      width: 48%;
      background-color: #fff;
      border-radius: 10rpx;
      overflow: hidden;

      .goods-item-img {
        display: flex;
        justify-content: center;
        height: 305rpx;
        width: 305rpx;
        overflow: hidden;
        margin: 0 auto;

        image {
          height: 100%;
          width: 100%;
        }
      }

      .goods-item-title {
        width: 85%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-top: 15rpx;
        color: #101010;
        font-size: 28rpx;
        line-height: 35rpx;
        padding: 0 18rpx;
      }

      .goods-item-buy {
        position: relative;
        padding: 0 18rpx 10rpx;

        .goods-item-price {
          font-size: 32rpx;
          color: darken($color: $custom-theme-red, $amount: 15%);
          line-height: 40rpx;
        }

        .goods-item-price-old {
          font-size: 18rpx;

          .price {
            text-decoration: line-through;
            color: #c0b8b5;
          }

          .sold {
            color: lighten($color: $custom-theme-red, $amount: 5%);
            font-size: 23rpx;
          }
        }

        .add-to-cart {
          position: absolute;
          bottom: 15rpx;
          right: 18rpx;
          display: flex;
          flex-direction: column;
          align-items: center;

          .icon {
            margin-bottom: 5rpx;
            background-color: $custom-theme-red;
            width: 50rpx;
            height: 50rpx;
            border-radius: 25rpx;
            text-align: center;
            line-height: 55rpx;
          }
        }
      }
    }
  }

}
</style>